package com.tom.joke.activity.selectimg;

import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.frame.library.BaseSkinActivity;
import com.frame.library.DefaultNavigationBar;
import com.frame.library.util.StatusBarUtil;
import com.tom.joke.R;

import java.io.File;
import java.util.ArrayList;

/**
 * 图片选择页面，可拍照。
 */
public class SelectImageActivity extends BaseSkinActivity {
    private static final String TAG = "SelectImageActivity";

    // 单选或多选，int类型的type值； boolean类型的 是否显示拍照按钮；
    // int类型的图片最多张数； ArrayList<String> 已经选择好的图片列表。
    // 选择图片的模式 -多选
    public static final int MODE_MULTI = 0x8011;
    // 选择图片的模式 -单选
    public static final int MODE_SINGLE = 0x0012;
    //是否显示相机的EXTRA_KEY
    public static final String EXTRA_SHOW_CAMERA = "EXTRA_SHOW_CAMERA";
    //总共可以选择多少张图片的EXTRA_KFY
    public static final String EXTRA_SELECT_COUNT = "EXTRA_SELECT_COUNT";
    //原始的图片路径的EXTRA_KEY
    public static final String EXTRA_DEFAULT_SELECTED_LIST = "EXTRA_DEFAULT_SELECTED_LIST";
    //选择模式的EXTRA_KEY
    public static final String EXTRA_SELECT_MODE = "EXTRA_SELECT_MODE";
    //返回选择图片列表的EXTRA_KEY
    public static final String EXTRA_RESULT = "EXTRA_RESULT";
    private TextView mSelectNumTv;
    // 查询所有数据
    private RecyclerView mImageListRv;
    // 加载所有的数据
    private static final int LOADER_TYPE = 0x0021;
    // 图片显示的Adapter
    private SelectImageListAdapter mImageAdapter;
    // 拍照临时存放的文件
    private File mTempFile;

    // 传递过来的参数
    private int mMode = MODE_MULTI;
    private int mMaxCount = 8;
    private boolean mShowCamera = true;
    private ArrayList<String> mResultList;
    private Button mCompleteSelectorBt;

    private TextView mSelectNum;
    private TextView mSelectPreview;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_select_image);
    }

    @Override
    protected void initTitle() {

    }

    @Override
    protected void initView() {
        DefaultNavigationBar navigationBar = new DefaultNavigationBar
                .Builder(this)
                .setTitleBackgroundColor(Color.parseColor("#261f1f"))
                .setTitle("所有图片")
                .builder();
        // 改变状态栏颜色
        StatusBarUtil.setStatusBarColor(this, Color.parseColor("#FF261f1f"));

        mImageListRv = findViewById(R.id.image_list_rv);
        mSelectNum = findViewById(R.id.select_num);
        mSelectPreview = findViewById(R.id.select_preview);
        mSelectPreview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO 图片的预览，支持放大缩小。
            }
        });
    }

    @Override
    protected void initData() {
        // 1.获取上一页，传过来的参数。
        Intent intent = getIntent();
        mMode = intent.getIntExtra(EXTRA_SELECT_MODE, mMode);
        mMaxCount = intent.getIntExtra(EXTRA_SELECT_COUNT, mMaxCount);
        mShowCamera = intent.getBooleanExtra(EXTRA_SHOW_CAMERA, mShowCamera);
        mResultList = intent.getStringArrayListExtra(EXTRA_DEFAULT_SELECTED_LIST);
        if (mResultList == null) {
            mResultList = new ArrayList<>();
        }
        // 2.初始化本地图片数据
        initImageList();
        // 3. 改变布局现实
        exchangeViewShow();
    }

    // 确定按钮，@OnClick(R.id.select_finish)
    private void confirmSelect() {
        // 选择好的图片，回传回去。
        Intent intent = new Intent();
        intent.putStringArrayListExtra(EXTRA_RESULT, mResultList);
        setResult(RESULT_OK, intent);
        finish();
    }


    // 选择item变化，需要及时更新。每次点击，都需要回调出来。
    private void exchangeViewShow() {
        // 预览按钮设置。修改按钮颜色
        if (mResultList.size() > 0) {
            mSelectPreview.setEnabled(true);
        } else {
            mSelectPreview.setEnabled(false);
        }
        // 中间图片的张数。
        mSelectNum.setText(mResultList.size() + "/" + mMaxCount);
    }

    // 2.从ContentProvider 获取图片。耗时操作。(开线程，AsyncTask，LoaderManager异步)
    private void initImageList() {
        // id: 查询全部
        getLoaderManager().initLoader(LOADER_TYPE, null, mLoaderCallback);
    }


    // 加载图片的callback
    private LoaderManager.LoaderCallbacks mLoaderCallback = new LoaderManager.LoaderCallbacks() {
        private final String[] IMAGE_PROJECTION = {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media.MIME_TYPE,
                MediaStore.Images.Media.SIZE,
                MediaStore.Images.Media._ID};

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            // 类似查询数据库, 查询语句
            CursorLoader cursorLoader = new CursorLoader(SelectImageActivity.this,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                    IMAGE_PROJECTION[4] + ">0 AND " + IMAGE_PROJECTION[3] + "=? OR "
                            + IMAGE_PROJECTION[3] + "=? ",
                    new String[]{"image/jpeg", "image/png"}, IMAGE_PROJECTION[2] + " DESC"
            );
            return cursorLoader;
        }

        @Override
        public void onLoadFinished(Loader loader, Object data) {
            Cursor cursor = (Cursor) data;
            // 如果有数据
            if (cursor != null && cursor.getCount() > 0) {
                ArrayList<String> images = new ArrayList<>();
                // 第一个位置，需要显示相机，就在第一个位置加""
                if (mShowCamera) {
                    images.add("");
                }
                // 遍历
                while (cursor.moveToNext()) {
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
//                    String name = cursor.getString(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
//                    long time = cursor.getLong(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                    images.add(path);
                }
                showListData(images);
            }
        }

        @Override
        public void onLoaderReset(Loader loader) {

        }
    };

    // 显示图片列表
    private void showListData(ArrayList<String> images) {
        Log.d(TAG, "imgLength:" + images);
        mImageAdapter = new SelectImageListAdapter(this, images, mResultList, mMaxCount);
        mImageListRv.setLayoutManager(new GridLayoutManager(this, 4));
//        mImageListRv.setAdapter(mImageAdapter);

        mImageAdapter.setOnSelectImgListener(new SelectImgListener() {
            @Override
            public void select() { // 通知布局更新
                exchangeViewShow();
            }
        });
    }

    // 去拍照
    public void openCamera(File file) {
        mTempFile = file;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    public static final int REQUEST_CAMERA = 90;
    // 拍完照的回调。
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 1. 拍的图片添加到集合；
        // 2. sureSelect()方法调用；
        // 3. 通知系统，本地有图片改变了。下次进来能看到拍照的图片。
        if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
            // notify system the image has changed.
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(mTempFile)));
            mResultList.add(mTempFile.getAbsolutePath());
            setResult();
        }
    }
    // 设置返回的结果。
    private void setResult() {
        Intent intent = new Intent();
        intent.putStringArrayListExtra(EXTRA_RESULT, mResultList);
        setResult(RESULT_OK, intent);
        finish();
    }


}
